package com.acmedcare.framework.exchange.center.core.storage;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Component;

@Component
public class RunnerRepository {

  private final JdbcTemplate jdbcTemplate;

  public RunnerRepository(JdbcTemplate jdbcTemplate) {
    this.jdbcTemplate = jdbcTemplate;
  }

  public void createRunner(TaskRunner runner) {

    String sql = " INSERT INTO qrtz_task_status (task_id,running,`name`,`count`,runner) VALUE(?,?,?,?,?)";
    jdbcTemplate.update(sql,
        new Object[]{runner.getTaskId(), runner.getRunning(), runner.getName(), runner.getCount(),
            runner.getRunner()});
  }

  public TaskRunner getRunner(Long taskId) {

    try {

      TaskRunner runner = jdbcTemplate
          .queryForObject("SELECT * FROM qrtz_task_status WHERE task_id=?", new Object[]{taskId},
              new
                  RunnerRowMapper());

      return runner;
    } catch (EmptyResultDataAccessException e) {

      return null;
    }
  }

  public List<TaskRunner> getRunning() {

    try {

      List<TaskRunner> runner = jdbcTemplate
          .query("SELECT * FROM qrtz_task_status where  count>0 ",
              new
                  RunnerRowMapper());

      return runner;
    } catch (EmptyResultDataAccessException e) {

      return null;
    }
  }

  public void addCount(Long taskId, String runnerName) {

    jdbcTemplate.update("UPDATE qrtz_task_status set count=count+1,runner=? WHERE task_id=?",
        new Object[]{runnerName, taskId});
  }

  public void deleteCount(Long taskId) {

    jdbcTemplate
        .update("UPDATE qrtz_task_status set count=count-1  WHERE task_id=?", new Object[]{taskId});
  }

  class RunnerRowMapper implements RowMapper<TaskRunner> {


    @Override
    public TaskRunner mapRow(ResultSet resultSet, int i) throws SQLException {

      TaskRunner runner = new TaskRunner();
      runner.setTaskId(resultSet.getLong("task_id"));
      runner.setName(resultSet.getString("name"));
      runner.setCount(resultSet.getInt("count"));
      runner.setRunning(resultSet.getBoolean("running"));
      runner.setRunner(resultSet.getString("runner"));
      runner.setUpdateTime(resultSet.getDate("update_time"));

      return runner;
    }
  }
}
